import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
import { getCookies } from '@/libs/auth'

const addErrorLog = errorInfo => {
  // TODO 对错误日志进行收集
}

class HttpRequest {

  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
      }
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // TODO页面取消正在加载的特效
    }
  }

  interceptors (instance, options) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // TODO根据不同框架添加不同的加载特效
      }
      this.queue[options.url] = true
      // 添加token
      // const token = store.getters.token
      // if (token && token != 'undefined') {
      //   config.headers['juyou.session.id'] = getCookies('token')
      // }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(options.url)
      const { data, status } = res
      Toast.clear()
      if (data.errcode === 1001) {
        let self_url = encodeURIComponent(window.location.href.replace(/#/g, '$'))
        let type = ''
      } else if (data.errcode === 10002) {
        Toast(data.errmsg)
        return { data }
      } else {
        return { data, status }
      }
    }, error => {
      this.destroy(options.url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }

  request (options) {
    if (options.loading == true) {
      Toast.loading({
        overlay: true,
        duration: 0,
        message: '加载中...'
      })
    }
    const instance = axios.create()
    if (options.type === 'get') {
      options.method = 'get'
      options.params = options.data
    } else {
      options.method = 'post'
    }

    delete options.type
    // 跨域是否携带凭证
    options.withCredentials = false

    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options)
    if (options.await === true) {
      return new Promise((resolve, reject) => {
        instance(options)
          .then((response) => {
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    } else {
      return instance(options)
    }
  }

}

export default HttpRequest
